﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace SP.FUPS
{
    [Serializable]
    public class LogFile
    {
        //properties
        private string _logDir;
        private string _logFileName;

        /// <summary>
        /// Initializes a new instance of the LogFile class with file prefix
        /// name and directory.
        /// </summary>
        /// <param name="logDirectory">Fully qualified directory name</param>
        /// <param name="filePrefix">Used to create log file name 
        ///  i.e. filePrefix + datetime + .log</param>
        /// <exception cref=" LogLibraryException">Thrown when exception creating file.</exception>
        public LogFile(string filePrefix, string logDirectory)
        {
            //set log directory
            if (logDirectory.Length > 0) //if logdirectory is set
            {
                this.logDir = logDirectory;
            }
            else //if constructor w/ just filePrefix, set directory to default
            {
                //get current directory
                string curDir = Directory.GetCurrentDirectory();

                //set default log directory
                this.logDir = curDir + @"\log";
            }

            //set log filename
            this.logFileName = filePrefix + DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".log";

            this.createLogFile();

            //create initial log entry
            this.createLogEntry("START", "Log file created");
        }


        /// <summary>
        /// Initializes a new instance of the LogFile class with the file prefix name. 
        /// The default directory of currentdir\log\ will be used
        /// </summary>
        /// <param name="filePrefix">log file will be named filePrefix + datetime + .log</param>
        public LogFile(string filePrefix)
            : this(filePrefix, "") { }


        //methods
        /// <summary>
        /// Checks if log directory exists.  If not, creates it and then creates file
        /// with _logFileName.
        /// </summary>
        private void createLogFile()
        {
            //If directory does not exist, create it.
            try
            {
                if (!Directory.Exists(_logDir))
                {
                    Directory.CreateDirectory(_logDir);
                }

                //change to log directory
                Directory.SetCurrentDirectory(_logDir);

                //create log file
                StreamWriter swLog = new StreamWriter(_logFileName);
                swLog.Close();

            }
            catch (System.IO.DirectoryNotFoundException)
            {
                //set log directory to current directory if creating dir causes exception
                _logDir = Directory.GetCurrentDirectory();
            }

            catch (Exception ex)
            {
                throw new LogLibraryException("Directory could not be found or created", ex);
            }

        }

        /// <summary>
        /// Writes a log entry to the log file starting with the date and time,
        /// then the type of log entry then the message.
        /// </summary>
        /// <param name="entryType">Type of log entry (e.g. Info, Error, etc.)</param>
        /// <param name="message">Log entry message</param>
        /// <exception cref=" LogLibraryException">Thrown when exception writing to log.</exception>
        public void createLogEntry(string entryType, string message)
        {
            try
            {
                string logEntry = DateTime.Now.ToString() + "  " + entryType + ": " + message;

                //append entry to log
                StreamWriter swLog = File.AppendText(_logFileName);
                swLog.WriteLine(logEntry);
                swLog.Close();

            }
            catch (Exception ex)
            {

                throw new LogLibraryException("Could not write to log: " + _logFileName, ex);
            }
        }

        /// <summary>
        /// Overloaded.  Writes a log entry to the log file starting with the date and time,
        /// then the ype of log entry then the message. Adds parameter for log filename.
        /// </summary>
        /// <param name="fileName">Fully qualified name of the log file to write to.</param>
        /// <param name="entryType">Thpe of log entry (e.g. Info, Error, etc.)</param>
        /// <param name="message">Log entry message.</param>
        /// <exception cref=" LogLibraryException">Thrown when exception writing to log.</exception>
        public void createLogEntry(string fileName, string entryType, string message)
        {
            try
            {
                string logEntry = DateTime.Now.ToString() + "  " + entryType + ": " + message;

                //append entry to log
                StreamWriter swLog = File.AppendText(fileName);
                swLog.WriteLine(logEntry);
                swLog.Close();

            }
            catch (Exception ex)
            {

                throw new LogLibraryException("Could not write to log: " + fileName, ex);
            }
        }

        /// <summary>
        /// Directory where log file will be created
        /// </summary>
        public string logDir
        {
            get { return _logDir; }
            set { _logDir = value; }
        }

        /// <summary>
        /// Name of the log file
        /// </summary>
        public string logFileName
        {
            get { return _logFileName; }
            set { _logFileName = value; }
        }
    }

    /// <summary>
    /// Custom exception handling.
    /// </summary>
    [Serializable]
    public class LogLibraryException : ApplicationException
    {
        public LogLibraryException() { }
        public LogLibraryException(string message) : base(message) { }
        public LogLibraryException(string message, Exception inner) : base(message, inner) { }
        protected LogLibraryException(
          System.Runtime.Serialization.SerializationInfo info,
          System.Runtime.Serialization.StreamingContext context)
            : base(info, context) { }
    }
}
